package com.yune.activity.main.ui.find;

import android.util.Log;

import androidx.lifecycle.ViewModel;

import com.yune.bean.SongBean;
import com.yune.utils.NetWorkCallback;
import com.yune.utils.Network;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLEncoder;

public class FindViewModel extends ViewModel {
    private static final String TAG = "emmmmmmmm";

    public FindViewModel() {

    }
    public void addSong(SongBean item,NetWorkCallback c) {
        String url="https://api2.bmob.cn/1/classes/song?where=" + URLEncoder.encode("{\"songId\":\""+item.songId+"\"}");
        Network.get(url, res->{
            if (res!=null){
                JSONObject jsonObject = new JSONObject(res);
                if (jsonObject.isNull("error")){//没有error
                    if (jsonObject.getJSONArray("results").length()==0){//没该歌，需添加
                        JSONObject jo=new JSONObject();
                        jo.put("songId",item.songId);
                        jo.put("picture",item.picture);
                        jo.put("singer",item.singer);
                        jo.put("songName",item.songName);
                        Network.post(jo, "https://api2.bmob.cn/1/classes/song", res1 -> {
                            if (res1!=null) {
                                String oid = new JSONObject(res1).getString("objectId");
                                c.callback(oid);
                            }
                        });
                    }else{//不管
                        c.callback(new JSONObject(res).getJSONArray("results").getJSONObject(0).getString("objectId"));
                    }
                }else{//有error需要添加song
                    JSONObject jo=new JSONObject();
                    jo.put("songId",item.songId);
                    jo.put("picture",item.picture);
                    jo.put("singer",item.singer);
                    jo.put("songName",item.songName);
                    Network.post(jo, "https://api2.bmob.cn/1/classes/song", res1 -> {
                        if (res1!=null) {
                            String oid = new JSONObject(res1).getString("objectId");
                            c.callback(oid);
                        }
                    });
                }
            }
        });
    }
}